<template>
  <div class="fic">
    <cube-button @click="send">show toast</cube-button>
    <div class="camera_outer">
      <video
        hidden="true"
        id="videoCamera"
        :width="videoWidth"
        :height="videoHeight"
        autoplay
      ></video>
      <canvas hidden="true"
        style="display: none"
        id="canvasCamera"
        :width="videoWidth"
        :height="videoHeight"
      ></canvas>
      <div v-if="imgSrc" class="img_bg_camera">
        <img :src="imgSrc" alt="" class="tx_img" hidden="true" />
      </div>
      <button @click="getCompetence()">打开摄像头</button>
      <button @click="stopNavigator()">关闭摄像头</button>
      <button @click="setImage()">拍照</button>
    </div>
  </div>
</template>
<script>
function blob2Str(blob) {
  var reader = new FileReader();
  reader.onload = function (event) {
    var theReader = event.target;
    var content = theReader.result;
    console.log(content);
  };
  reader.readAsText(blob);
}

function blob2Sound(blob) {}
function str2ArrayBuffer(str) {
  var buf = new ArrayBuffer(str.length); // 每个字符占用2个字节
  var bufView = new Uint8Array(buf);
  for (var i = 0, strLen = str.length; i < strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return buf;
}
function dataURItoBlob(dataURI) {
  var byteString = atob(dataURI.split(",")[1]);
  var mimeString = dataURI.split(",")[0].split(":")[1].split(";")[0];
  var ab = new ArrayBuffer(byteString.length);
  var ia = new Uint8Array(ab);
  for (var i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }
  return new Blob([ab], { type: mimeString });
}
export default {
  name: "Fic",
  data() {
    return {
      lastTick: 0,
      working: false,
      timer: null,
      path: "ws://127.0.0.1:9090/ws/pic?groupToken=d380c20b399d4d0ba4bd2c178a297b52:1627195053654:ToWJtG7o/XhHpudaUpYQNI2BTSo=",
      socket: null,
      params: "hello",

      videoWidth: 300,
      videoHeight: 300,
      imgSrc: "",
      imgBlob: null,
      thisCancas: null,
      thisContext: null,
      thisVideo: null,

      soundCtx: null,
      soundBuf: null,
    };
  },
  mounted() {
    // 初始化
    this.init();
    this.timer = setInterval(this.setImage, 2000);
  },
  methods: {
    init: function () {
      if (typeof WebSocket === "undefined") {
        alert("您的浏览器不支持socket");
      } else {
        // 实例化socket
        this.socket = new WebSocket(this.path);
        // 监听socket连接
        this.socket.onopen = this.open;
        // 监听socket错误信息
        this.socket.onerror = this.error;
        // 监听socket消息
        this.socket.onmessage = this.getMessage;
        this.socket.onclose = this.close;
      }
      if (!window.AudioContext) {
        if (!window.webkitAudioContext) {
          alert(
            "Your browser does not support any AudioContext and cannot play back this audio."
          );
          return;
        }
        window.AudioContext = window.webkitAudioContext;
      }
      this.soundCtx = new AudioContext();
    },
    playByteArray: function (blob) {
      console.log(blob);
      console.log("playByteArray");
      // var arrayBuffer = new ArrayBuffer(byteArray.length);
      // var bufferView = new Uint8Array(arrayBuffer);
      // for (var i = 0; i < byteArray.length; i++) {
      //   bufferView[i] = byteArray[i];
      // }
      var arrayBuffer;
      var fileReader = new FileReader();
      var _this = this;
      fileReader.onload = function(event) {
        console.log("fileReader onload");
        arrayBuffer = event.target.result;
        _this.soundCtx.decodeAudioData(arrayBuffer, function (buffer) {
          console.log("decodeAudioData cb");
          _this.soundBuf = buffer;
          _this.play();
        });
      };
      fileReader.readAsArrayBuffer(blob);
    },
    // Play the loaded file
    play: function () {
      console.log("play");
      // Create a source node from the buffer
      var source = this.soundCtx.createBufferSource();
      source.buffer = this.soundBuf;
      // Connect to the final output node (the speakers)
      source.connect(this.soundCtx.destination);
      // Play immediately
      source.start(0);
    },
    restart: function () {
      if (!working) {
        return;
      }
      this.socket = new WebSocket(this.path);
      // 监听socket连接
      this.socket.onopen = this.open;
      // 监听socket错误信息
      this.socket.onerror = this.error;
      // 监听socket消息
      this.socket.onmessage = this.getMessage;
      this.socket.onclose = this.close;
    },
    open: function () {
      this.working = true;
      console.log("socket连接成功");
    },
    error: function () {
      console.log("连接错误");
    },
    getMessage: function (msg) {
      console.log("getMessage");
      this.playByteArray(msg.data);
      // blob2Str(msg.data);
    },
    send: function () {
      if (!this.working) {
        this.socket.close();
        return;
      }
      // console.log((this.imgSrc))
      var blob = dataURItoBlob(this.imgSrc);
      this.socket.send(blob);
    },
    close: function () {
      if (this.working) {
        this.restart();
      }
      console.log("socket已经关闭");
    },
    destroyed() {
      // 销毁监听
      this.socket.onclose = this.close;
    },
    getCompetence() {
      var _this = this;
      this.thisCancas = document.getElementById("canvasCamera");
      this.thisContext = this.thisCancas.getContext("2d");
      this.thisVideo = document.getElementById("videoCamera");
      // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {};
      }
      // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
      // 使用getUserMedia，因为它会覆盖现有的属性。
      // 这里，如果缺少getUserMedia属性，就添加它。
      if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function (constraints) {
          // 首先获取现存的getUserMedia(如果存在)
          var getUserMedia =
            navigator.webkitGetUserMedia ||
            navigator.mozGetUserMedia ||
            navigator.getUserMedia;
          // 有些浏览器不支持，会返回错误信息
          // 保持接口一致
          if (!getUserMedia) {
            return Promise.reject(
              new Error("getUserMedia is not implemented in this browser")
            );
          }
          // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
          return new Promise(function (resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject);
          });
        };
      }
      var constraints = {
        audio: false,
        video: {
          width: this.videoWidth,
          height: this.videoHeight,
          transform: "scaleX(-1)",
        },
      };
      navigator.mediaDevices
        .getUserMedia(constraints)
        .then(function (stream) {
          // 旧的浏览器可能没有srcObject
          if ("srcObject" in _this.thisVideo) {
            _this.thisVideo.srcObject = stream;
          } else {
            // 避免在新的浏览器中使用它，因为它正在被弃用。
            _this.thisVideo.src = window.URL.createObjectURL(stream);
          }
          _this.thisVideo.onloadedmetadata = function (e) {
            _this.thisVideo.play();
          };
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //  绘制图片（拍照功能）
    setImage() {
      if (this.socket) var _this = this;
      // 点击，canvas画图
      _this.thisContext.drawImage(
        _this.thisVideo,
        0,
        0,
        _this.videoWidth,
        _this.videoHeight
      );
      // 获取图片base64链接
      var image = this.thisCancas.toDataURL("image/jepg");

      _this.imgSrc = image;
      this.send();
      this.$emit("refreshDataList", this.imgSrc);
    },
    // base64转文件
    dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(",");
      var mime = arr[0].match(/:(.*?);/)[1];
      var bstr = atob(arr[1]);
      var n = bstr.length;
      var u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    },
    // 关闭摄像头
    stopNavigator() {
      this.working = false;
      this.socket.close();
      this.thisVideo.srcObject.getTracks()[0].stop();
    },
  },
};
</script>
